package controllers

import (
	"c111/cache"
	"c111/models"
	"c111/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UseController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UseController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	pwd := pkg.Md5(password)
	var use models.Use
	use.Username = username
	use.Password = pwd
	err := models.DB.Create(&use).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *UseController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var use models.Use
	use.Username = username
	err := models.DB.Where("username=?", username).First(&use).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	key := "use_login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if errCount >= 3 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "密码错误次数过多，请稍后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if use.Password != password {
		cache.Rdb.Incr(cache.Ctx, key)
		if errCount == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "登录成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
